package com.zlx.sharelive.activity;

import android.app.Dialog;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.lzj.pass.dialog.PayPassDialog;
import com.lzj.pass.dialog.PayPassView;
import com.zlx.module_base.base_ac.BaseAc;
import com.zlx.module_base.base_api.res_data.AuctionFriendDetailsBean;
import com.zlx.module_base.base_api.res_data.AuctionTradingBody;
import com.zlx.module_base.base_api.res_data.BaseBean;
import com.zlx.module_base.base_api.res_data.PurchaseVideoBean;
import com.zlx.module_base.base_api.res_data.QueryByBean;
import com.zlx.module_base.base_api.util.ApiUtil;
import com.zlx.module_base.base_util.SPUtil;
import com.zlx.module_network.api1.livedata.BaseObserver;
import com.zlx.module_network.api1.livedata.BaseObserverCallBack;
import com.zlx.module_network.bean.ApiResponse;
import com.zlx.sharelive.Constants;
import com.zlx.sharelive.R;
import com.zlx.sharelive.adapter.CommonRecyclerViewAdapter;
import com.zlx.sharelive.adapter.CommonRecyclerViewHolder;
import com.zlx.sharelive.utils.GlideImgManager;
import com.zlx.sharelive.utils.StringUt;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import in.xiandan.countdowntimer.CountDownTimerSupport;
import in.xiandan.countdowntimer.OnCountDownTimerListener;

/**
 * 竞拍详情
 */
public class AuctionDetailsAc extends BaseAc {

    @BindView(R.id.iv_head)
    ImageView iv_head;
    @BindView(R.id.tv_recommend_nickname)
    TextView tv_recommend_nickname;
    @BindView(R.id.tv_phone)
    TextView tv_phone;
    @BindView(R.id.tv_up_phone)
    TextView tv_up_phone;
    @BindView(R.id.tv_time)
    TextView tv_time;
    @BindView(R.id.tv_time2)
    TextView tv_time2;
    @BindView(R.id.tv_earnest_money)
    TextView tv_earnest_money;
    @BindView(R.id.tv_money)
    TextView tv_money;
    @BindView(R.id.rv_data)
    RecyclerView rv_data;
    @BindView(R.id.tv_comm)
    TextView tv_comm;
    @BindView(R.id.ll_time)
    LinearLayout ll_time;

    private String type = "";
    private String over = "";
    private String id;
    private AuctionFriendDetailsBean.InfoDTO mAuctionFriendDetailsBean;
    private List<AuctionFriendDetailsBean.InfoDTO.ListDTO> mList = new ArrayList<>();
    private CommonRecyclerViewAdapter<AuctionFriendDetailsBean.InfoDTO.ListDTO> mAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.ac_auction_details;
    }

    @Override
    public void initViews() {
        super.initViews();

        type = getIntent().getStringExtra("type");
        id = getIntent().getStringExtra("id");

        if (type.equals("1")) {
            tv_comm.setVisibility(View.VISIBLE);
        } else {
            tv_comm.setVisibility(View.GONE);
        }

        getAuctionFriend();
        initRecyclerView();
        queryById();
    }

    /**
     * 查询余额
     */
    private void queryById() {
        ApiUtil.getLoginApi().queryById(SPUtil.getToken(this),(String) SPUtil.get(this, Constants.SP_ID, ""))
                .observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<QueryByBean>>() {
                    @Override
                    public void onSuccess(ApiResponse<QueryByBean> data) {
                        if (null != data) {
                            if (null != data.getData()) {
                                if (null != data.getData().getInfo()) {
                                    if (data.getData().getInfo().size() > 0) {
                                        if (null != data.getData().getInfo().get(0).getResult()) {
                                            if (!StringUt.isEmpty(data.getData().getInfo().get(0).getResult().getMoney())) {
                                                over = data.getData().getInfo().get(0).getResult().getMoney();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();

                    }
                }));
    }

    private void getAuctionFriend() {
        ApiUtil.getFriendApi().getAuctionFriend(SPUtil.getToken(this),
                id).observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<AuctionFriendDetailsBean>>() {
            @Override
            public void onSuccess(ApiResponse<AuctionFriendDetailsBean> data) {
                mList.clear();
                if (null != data) {
                    if (null != data.getData()) {
                        if (null != data.getData().getInfo()) {
                            if (data.getData().getInfo().size() > 0) {
                                mAuctionFriendDetailsBean = data.getData().getInfo().get(0);
                                if (null != data.getData().getInfo().get(0).getList()) {
                                    mList.addAll(data.getData().getInfo().get(0).getList());
                                }
                                setData();
                            }
                        }
                    }
                }
                mAdapter.notifyDataSetChanged();
            }
        }));
    }

    private void setData() {
        GlideImgManager.glideLoader(this, mAuctionFriendDetailsBean.getAvatar(), iv_head, 0);
        tv_recommend_nickname.setText(mAuctionFriendDetailsBean.getNickName());
        tv_up_phone.setText(mAuctionFriendDetailsBean.getUphone());
        tv_phone.setText(mAuctionFriendDetailsBean.getFriendPhone());
        tv_time.setText(mAuctionFriendDetailsBean.getCreateTime());
        if (StringUt.isEmpty(mAuctionFriendDetailsBean.getTime())) {
            ll_time.setVisibility(View.GONE);
            tv_comm.setVisibility(View.GONE);
        } else {
            setTime(tv_time2, Long.valueOf(mAuctionFriendDetailsBean.getTime()) * 1000);
        }
        tv_earnest_money.setText("￥" + mAuctionFriendDetailsBean.getEarnestMoney());
        tv_money.setText("￥" + mAuctionFriendDetailsBean.getMoney());
    }

    /**
     * 初始化拍卖记录
     */
    private void initRecyclerView() {
        rv_data.setLayoutManager(new LinearLayoutManager(this));

        mAdapter = new CommonRecyclerViewAdapter<AuctionFriendDetailsBean.InfoDTO.ListDTO>(this, mList) {
            @Override
            public void convert(CommonRecyclerViewHolder holder, AuctionFriendDetailsBean.InfoDTO.ListDTO entity, int position) {
                GlideImgManager.glideLoader(AuctionDetailsAc.this, entity.getAvatar(), holder.getView(R.id.iv_details_head), 0);
                holder.setText(R.id.tv_nickname, entity.getNickName());
                holder.setText(R.id.tv_money, "￥" + entity.getMoney());
                holder.setText(R.id.tv_time, entity.getCreateTime());
            }

            @Override
            public int getLayoutViewId(int viewType) {
                return R.layout.item_auction_details;
            }
        };

        rv_data.setAdapter(mAdapter);
    }

    /**
     * 倒计时
     */
    private void setTime(TextView tv_time, long time) {
        //毫秒
        CountDownTimerSupport mTimer = new CountDownTimerSupport(time, 100);
        mTimer.setOnCountDownTimerListener(new OnCountDownTimerListener() {
            @Override
            public void onTick(long millisUntilFinished) {
                // 倒计时间隔
                tv_time.setText(formatDuring(millisUntilFinished));
            }

            @Override
            public void onFinish() {
                // 倒计时结束
                tv_time.setText("倒计时结束");
            }

            @Override
            public void onCancel() {
                // 倒计时手动停止
            }
        });
        mTimer.start();
    }

    public static String formatDuring(long mss) {

        long days = mss / (1000 * 60 * 60 * 24);

        long hours = (mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);

        long minutes = (mss % (1000 * 60 * 60)) / (1000 * 60);

        long seconds = (mss % (1000 * 60)) / 1000;

        return days + " 天 " + hours + ":" + minutes + ":"

                + seconds;

    }


    @OnClick(R.id.tv_comm)
    public void setOnClick(View view) {
        switch (view.getId()) {
            case R.id.tv_comm:
                if (!StringUt.isEmpty(mAuctionFriendDetailsBean.getIsSecurity())) {
                    if (mAuctionFriendDetailsBean.getIsSecurity().equals("2")) {
                        //已交保证金 可以直接拍
                        dialogMarkUp();
                    } else {
                        dialog(id);
                    }
                }
                break;
        }
    }

    /**
     * 缴纳金
     */
    private void dialog(String id) {
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(this, R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(this, R.layout.dialog_pay2, null);
        dialog.setContentView(view);

        TextView tv_comm = view.findViewById(R.id.tv_comm);

        tv_comm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialogPay(id, "1000", dialog);
            }
        });

        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.CENTER);
        //设置弹出动画
        window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();

    }

    /**
     * 购买
     */
    private void dialogPay(String id, String money, Dialog mDialog) {
        mDialog.dismiss();
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(this, R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(this, R.layout.dialog_play_video, null);
        dialog.setContentView(view);

        TextView tv_money = view.findViewById(R.id.tv_money);
        tv_money.setText("￥" + money);

        TextView tv_over = view.findViewById(R.id.tv_over);
        tv_over.setText("￥" + over);

        TextView bt_play = view.findViewById(R.id.bt_play);

        bt_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!StringUt.isEmpty(money) && !StringUt.isEmpty(over)) {
                    if (Double.valueOf(over) > Double.valueOf(money)) {
                        //钱够支付
                        dialogPass(id, money);
                        dialog.dismiss();
                    }
                }
            }
        });

        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.BOTTOM);
        //设置弹出动画
//        window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();

    }

    /**
     * 支付密码
     */
    private void dialogPass(String id, String money) {
        PurchaseVideoBean purchaseVideoBean = new PurchaseVideoBean();
        purchaseVideoBean.setId(id);
        purchaseVideoBean.setMoney(money);

        final PayPassDialog dialog = new PayPassDialog(this);
        dialog.getPayViewPass()
                .setRandomNumber(true)
                .setPayClickListener(new PayPassView.OnPayClickListener() {
                    @Override
                    public void onPassFinish(String passContent) {
                        //6位输入完成回调
                        Log.d("ret", "joker  输入的密码===" + passContent);
                        goToPay(id, money, passContent, dialog);
                        dialog.dismiss();
                    }

                    @Override
                    public void onPayClose() {
                        dialog.dismiss();
                        //关闭弹框
                    }

                    @Override
                    public void onPayForget() {
                        dialog.dismiss();
                        //点击忘记密码回调
                    }
                });

    }

    /**
     * 缴纳金
     */
    private void goToPay(String id, String money, String pass, PayPassDialog dialog) {
        ApiUtil.getFriendApi().goToPay(SPUtil.getToken(this),
                "2",
                money,
                id,
                pass
        ).observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<BaseBean>>() {
            @Override
            public void onSuccess(ApiResponse<BaseBean> data) {
                if (null != data) {
                    if (null != data.getData()) {
                        if (data.getData().getCode() == 0) {
                            dialogMarkUp();
                        } else {
                            Toast.makeText(AuctionDetailsAc.this, data.getData().getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }
        }));
    }

    /**
     * 加价
     */
    private void dialogMarkUp() {
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(this, R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(this, R.layout.dialog_mark_up, null);
        dialog.setContentView(view);

        TextView tv_money = view.findViewById(R.id.tv_money);
        Button bt_play = view.findViewById(R.id.bt_play);

        ImageView iv_jian = view.findViewById(R.id.iv_jian);
        ImageView iv_jia = view.findViewById(R.id.iv_jia);

        if (!StringUt.isEmpty(mAuctionFriendDetailsBean.getBigMoney())) {
            if (Double.valueOf(mAuctionFriendDetailsBean.getBigMoney()) == 0) {
                //没有竞拍者
                tv_money.setText(mAuctionFriendDetailsBean.getMoney());
            } else {
                tv_money.setText(mAuctionFriendDetailsBean.getBigMoney());
            }
        }

        iv_jian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!StringUt.isEmpty(mAuctionFriendDetailsBean.getBigMoney())) {
                    if (Double.valueOf(mAuctionFriendDetailsBean.getBigMoney()) == 0) {
                        if (Double.valueOf(tv_money.getText().toString().trim()) <
                                Double.valueOf(mAuctionFriendDetailsBean.getMoney()) + 100) {
                            Toast.makeText(AuctionDetailsAc.this, "不能低于当前竞拍价格", Toast.LENGTH_SHORT).show();
                            return;
                        } else {
                            tv_money.setText(String.valueOf(Double.valueOf(tv_money.getText().toString().trim()) - 100));
                        }
                    } else {
                        if (Double.valueOf(tv_money.getText().toString().trim()) <
                                Double.valueOf(mAuctionFriendDetailsBean.getBigMoney()) + 100) {
                            Toast.makeText(AuctionDetailsAc.this, "不能低于当前竞拍价格", Toast.LENGTH_SHORT).show();
                            return;
                        } else {
                            tv_money.setText(String.valueOf(Double.valueOf(tv_money.getText().toString().trim()) - 100));
                        }
                    }
                } else {
                    if (Double.valueOf(tv_money.getText().toString().trim()) <
                            Double.valueOf(mAuctionFriendDetailsBean.getBigMoney()) + 100) {
                        Toast.makeText(AuctionDetailsAc.this, "不能低于当前竞拍价格", Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        tv_money.setText(String.valueOf(Double.valueOf(tv_money.getText().toString().trim()) - 100));
                    }
                }
            }
        });

        iv_jia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tv_money.setText(String.valueOf(Double.valueOf(tv_money.getText().toString().trim()) + 100));
            }
        });


        bt_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!StringUt.isEmpty(tv_money.getText().toString().trim()) && !StringUt.isEmpty(over)) {
                    if (Double.valueOf(over) > Double.valueOf(tv_money.getText().toString().trim())) {
                        //钱够支付
                        auctionTrading(tv_money.getText().toString().trim());
                        dialog.dismiss();
                    }
                }
            }
        });

        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.BOTTOM);
        //设置弹出动画
//        window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();

    }

    /**
     * 参与竞拍
     *
     * @param money
     */
    private void auctionTrading(String money) {
        AuctionTradingBody auctionTradingBody = new AuctionTradingBody();
        auctionTradingBody.setId(id);
        auctionTradingBody.setMoney(money);
        ApiUtil.getFriendApi().auctionTrading(SPUtil.getToken(this),
                id,
                money
        ).observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<BaseBean>>() {
            @Override
            public void onSuccess(ApiResponse<BaseBean> data) {
                if (data.getData().getCode() == 0) {
                    Toast.makeText(AuctionDetailsAc.this, "竞拍成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(AuctionDetailsAc.this, data.getData().getMsg(), Toast.LENGTH_SHORT).show();
                }
                getAuctionFriend();
                queryById();
            }
        }));
    }


}
